package online.sixfish.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import online.sixfish.common.dto.PageDTO;
import online.sixfish.common.exception.CommonConstant;
import online.sixfish.common.utils.SecurityUtil;
import online.sixfish.doubao.mapper.StudyGuideCommentMapper;
import online.sixfish.doubao.mapper.StudyGuideMapper;
import online.sixfish.doubao.model.dto.AddStudyGuideDTO;
import online.sixfish.doubao.model.entity.StudyGuide;
import online.sixfish.doubao.model.entity.StudyGuideComment;
import online.sixfish.doubao.service.StudyGuideService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class StudyGuideServiceImpl implements StudyGuideService {
    @Resource
    StudyGuideMapper studyGuideMapper;
    @Resource
    StudyGuideCommentMapper studyGuideCommentMapper;

    @Override
    public PageDTO<StudyGuide> list(Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<StudyGuide> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(StudyGuide::getStatus, CommonConstant.SYS_ILLEGAL_STATUS);
        Page<StudyGuide> page = new Page<>(pageNum, pageSize);
        studyGuideMapper.selectPage(page, queryWrapper);
        return PageDTO.build(page);
    }

    @Override
    public String add(AddStudyGuideDTO addStudyGuideDTO) {
        StudyGuide studyGuide = new StudyGuide();
        BeanUtils.copyProperties(addStudyGuideDTO, studyGuide);
        studyGuide.setUserId(SecurityUtil.currentUserId());
        studyGuideMapper.insert(studyGuide);


        return studyGuide.getId();
    }

    @Override
    public StudyGuide getById(String id) {
        LambdaUpdateWrapper<StudyGuide> wrapper = Wrappers
                .lambdaUpdate(StudyGuide.class).eq(StudyGuide::getId, id);
        wrapper.setSql("view=view+1");
        studyGuideMapper.update(null,wrapper);
        return studyGuideMapper.selectById(id);
    }

    @Override
    public void addComment(StudyGuideComment comment) {
        comment.setUserId(SecurityUtil.currentUserId());
        studyGuideCommentMapper.insert(comment);
    }

    @Override
    public PageDTO listComment(String id, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<StudyGuideComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudyGuideComment::getStudyGuideId, id);
        Page<StudyGuideComment> page = new Page<>(pageNum, pageSize);
        Page<StudyGuideComment> commentPage = studyGuideCommentMapper.selectPage(page, wrapper);
        return PageDTO.build(commentPage);

    }
}
